package com.gl.library.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.CursorLoader;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.http.SslCertificate;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Random;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 系统工具类
 * 
 */
public final class CommUtils {

	private static final String TAG = "Utils";

	/**
	 * 取得可用存储路径
	 * @return
	 */
	public static String getExternalStoragePath(Context context, String fileDir) {
		String dirPath = null;
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			if (Environment.getExternalStorageDirectory().canWrite()) {
				dirPath = Environment.getExternalStorageDirectory().getPath();
			} else {
				Log.w("TAG", "没有SD卡读写权限");
			}
		}else{
			dirPath = context.getFilesDir().getAbsolutePath();
		}
		File file = new File(dirPath+"/"+fileDir);
		if (!file.exists()) {
			file.mkdirs();
		}
		return file.getAbsolutePath();
	}

	/**
	 * 获得设备识别认证码
	 *
	 * @return
	 */
	public static String getIMEI(Context context) {
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		if (tm == null) {
			return null;
		}
		return tm.getDeviceId();
	}


	/**
	 * 判断设备是否存在SDcard卡
	 * 
	 */
	public static boolean hasSdCard() {
		boolean blFlagForSdCard = false;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			blFlagForSdCard = true;
		} else {
			blFlagForSdCard = false;
		}
		return blFlagForSdCard;
	}

	/**
	 * 检查手机上是否安装了指定的软件
	 *
	 * @param context
	 * @param packageName：应用包名
	 * @return
	 */
	public static boolean isInstalled(Context context, String packageName) {
		final PackageManager packageManager = context.getPackageManager();
		List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(0);
		if (packageInfoList != null) {
			for (PackageInfo info : packageInfoList) {
				if (packageName.equals(info.packageName)) return true;
			}
		}
		return false;
	}

	/**
	 * 为String生成MD5码
	 * 
	 * @param str
	 * @return
	 */
	public static String md5Encode(String str) {
		MessageDigest md = null;
		String dstr = null;
		try {
			md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());// update处理
			byte[] encryStr = md.digest();// 调用该方法完成计算
			int i;
			StringBuffer buf = new StringBuffer("");
			// 做相应的转化（十六进制）
			for (int offset = 0; offset < encryStr.length; offset++) {
				i = encryStr[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			dstr = buf.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return dstr;
	}

	/**
	 * 获取随机数
	 * 
	 * @return
	 */
	public static int getRandom() {
		int randomNum = 0;
		Random random = new Random();
		randomNum = random.nextInt(14);
		random = null;
		return randomNum;
	}

	/**
	 * 计算两个数的百分比
	 * 
	 * @param numer
	 * @param denom
	 * @return
	 */
	public static String getPercent(int numer, int denom) {
		NumberFormat numberFormat = NumberFormat.getInstance();
		// 设置精确到小数点后2位
		numberFormat.setMaximumFractionDigits(2);
		String result = numberFormat
				.format((float) numer / (float) denom * 100) + " %";
		return result;
	}

	/**
	 * 保留小数点后两位
	 * 
	 * @param decimalStr
	 * @return
	 */
	public static String decimalFormat(String decimalStr) {
		double decimal = Double.valueOf(decimalStr);
		DecimalFormat df = new DecimalFormat("#0.00");
		return df.format(decimal);
	}

	/**
	 * 获取系统时间戳(截取前10位)
	 */
	public static long getCurrSysTimeSeconds() {
		long currTimeSeconds = System.currentTimeMillis() / 1000;
		return currTimeSeconds;
	}

	/**
	 * 获取系统时间戳
	 * 
	 * @return
	 */
	public static long getCurrentTimeMillis() {
		long currTimeSeconds = System.currentTimeMillis();
		return currTimeSeconds;
	}

	/**
	 * 获取当前时间
	 */
	public static String getCurrentFormatTime() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = dateFormat.format(new Date());
		return time;
	}

	/**
	 * 获取当前时间
	 */
	public static String getCurrentFormatTimeByDay() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String time = dateFormat.format(new Date());
		return time;
	}
	/**
	 * 获取当前时间2
	 */
	public static String getCurrentFormatTime2() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
		String time = dateFormat.format(new Date());
		return time;
	}
	/**
	 * 获取指定格式时间
	 */
	public static String getSimpleFormatDate(String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		String sd = sdf.format(new Date());
		return sd;
	}

	/**
	 * 时间戳转换日期时间格式
	 */
	public static String getMillisMinuteDate(long millis, String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		String sd = sdf.format(new Date(millis * 1000));
		return sd;
	}

	/**
	 * 时间戳转换日期时间格式
	 */
	public static String getMillisSecsDate(long millis, String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		String sd = sdf.format(new Date(millis));
		return sd;
	}


	/**
	 * yyyy-MM-dd HH:mm:ss转换为HH:mm
	 * @throws ParseException
	 */
	public static String transferFormat(String inTime) throws ParseException{
		SimpleDateFormat format = new SimpleDateFormat("HH:mm");
		Date d1;
		Date d3 = null;
		try {
			d1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(inTime);
			String d2 = format.format(d1);
			d3 = format.parse(d2);
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		return format.format(d3);
	}


	/**
	 * 获取指定日期
	 * 
	 * @param days
	 *            -1 昨天 0 今天 1 明天
	 * @return
	 */
	public static String getSysDate(int days) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.DAY_OF_MONTH, days);
		Date date = calendar.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String sd = sdf.format(date);
		return sd;
	}

	/**
	 * 秒转换分钟
	 *
	 * @return
	 */
	public static String timeConver(long lsecond) {
		int second = (int) lsecond;
		int theDay = 24 * 60 * 60;// 一天
		int theHour = 60 * 60; // 一小时
		int theMinutes = 60; // 一分钟
		int nowTime = 0; // 当前的总秒数
		int nowDay = 0, nowHour = 0, nowMinutes = 0, nowSenconds = 0; // 现在的天数，小时，分，秒
		StringBuffer sb = new StringBuffer();
		if (second - theDay >= 0) { // 显示：天，小时
			nowDay = second / theDay;
			nowTime = second % theDay;
			if (nowTime - theHour >= 0) {
				nowHour = nowTime / theHour;
			} else {
				theHour = 0;
			}
			sb.append(nowDay + "天");
			sb.append(nowHour + "小时");
		} else if (second - theHour >= 0) {// 显示：小时，分钟
			nowHour = second / theHour;
			nowTime = second % theHour;
			if (nowTime - theMinutes >= 0) {
				nowMinutes = nowTime / theMinutes;
			} else {
				nowMinutes = 0;
				sb.append(nowHour + "小时");
				sb.append(nowMinutes + "分钟");
			}
		} else if (second - theHour < 0 && second - theMinutes >= 0) {// 显示：分钟
			nowMinutes = second / theMinutes;
			sb.append(nowMinutes + "分");
		} else {
			nowSenconds = second;
			sb.append(nowSenconds + "秒");
		}
		return sb.toString();
	}
	/**
	 * 分钟转换分钟/小时/天
	 *
	 * @return
	 */
	public static String newTimeConver(int myMinute) {
		int theDay = 24 * 60;// 一天
		int theHour = 60; // 一小时
		int theMinutes = myMinute; // 一分钟
		int nowDay = 0, nowHour = 0, nowMinutes = 0; // 现在的天数，小时，分
		String str_result = "";
		if (theMinutes - theDay >= 0) { // 显示：天
			nowDay = theMinutes / theDay;
			str_result = nowDay + "天前";
		} else if (theMinutes - theHour >= 0) {// 显示：小时
			nowHour = theMinutes / theHour;
			str_result = nowHour + "小时前";
		} else{// 显示：分钟
			str_result = theMinutes + "分前";
		}
		return str_result;
	}

	/**
	 * 过去时间格式化类
	 * @param millisTime
	 * @return
	 */
	public static String getFormatDate(long millisTime) {
		long diffValue = 0L;
		String convertTime = null;
		if (millisTime > 0) {
			long currTime = System.currentTimeMillis();
			diffValue = (currTime - millisTime) / 1000L;
			int xcts = (int) (diffValue / (24 * 60 * 60));
			if (diffValue > 0 && diffValue < 86400) {
				convertTime = "今天";
			} else if (diffValue > 86400 && xcts == 1) {
				convertTime = "昨天";
			} else if (diffValue > 86400 && xcts == 2) {
				convertTime = "前天";
			} else {
				SimpleDateFormat dateFormatTemp = new SimpleDateFormat(
						"yyyy年MM月dd日");
				convertTime = dateFormatTemp.format(new Date(millisTime));
			}
		}
		return convertTime;
	}
	
	/**
	 * 未来时间格式化类
	 * @param millisTime
	 * @return
	 */
	public static String getFormatTime(long millisTime) {
		String convertTime = null;
		Calendar current = Calendar.getInstance();
		Calendar today = Calendar.getInstance();	//明天0点
		today.set(Calendar.YEAR, current.get(Calendar.YEAR));
		today.set(Calendar.MONTH, current.get(Calendar.MONTH));
		today.set(Calendar.DAY_OF_MONTH,current.get(Calendar.DAY_OF_MONTH));
		today.set(Calendar.HOUR_OF_DAY, 23);
		today.set(Calendar.MINUTE, 59);
		today.set(Calendar.SECOND, 59);
		Calendar tomorrow = Calendar.getInstance();	//后天0点
		tomorrow.set(Calendar.YEAR, current.get(Calendar.YEAR));
		tomorrow.set(Calendar.MONTH, current.get(Calendar.MONTH));
		tomorrow.set(Calendar.DAY_OF_MONTH,current.get(Calendar.DAY_OF_MONTH)+1);
		tomorrow.set( Calendar.HOUR_OF_DAY, 23);
		tomorrow.set( Calendar.MINUTE, 59);
		tomorrow.set(Calendar.SECOND, 59);
		SimpleDateFormat dateFormatTemp = null;
		current.setTime(new Date(millisTime));
		if (millisTime > 0) {
			if(current.before(today)){
				dateFormatTemp = new SimpleDateFormat("今天 HH:mm");
			}else if(current.after(today) && current.before(tomorrow)){
				dateFormatTemp = new SimpleDateFormat("明天 HH:mm");
			}else if (current.after(tomorrow)) {
				dateFormatTemp = new SimpleDateFormat("MM月dd日 HH:mm");
			}
			convertTime = dateFormatTemp.format(new Date(millisTime));
		}
		return convertTime;
	}
	
	/**
	 * 时间格式化类
	 * @param srcTime
	 * @return
	 */
    public static String getFormatDate(String srcTime) {
        long diffValue = 0L;
        String convertTime = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long millisTime = 0;
        try {
            millisTime = dateFormat.parse(srcTime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (millisTime > 0) {
            long currTime = System.currentTimeMillis();
            diffValue = (currTime - millisTime) / 1000L;
            if (diffValue > 0 && diffValue < 86400) {
                convertTime = "今日";
            } else {
                dateFormat.applyPattern("MM月dd日");
                convertTime = dateFormat.format(new Date(millisTime));
            }
        }
        return convertTime;
    }

	/**
	 * 格式化时间戳
	 * 
	 * @param millis
	 * @return
	 */
	public static long getFormatMillis(long millis) {
		long parseTime = 0L;
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String formatTime = dateFormat.format(new Date(millis));
		try {
			parseTime = dateFormat.parse(formatTime).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return parseTime;
	}

	/**
	 * 时间字符串格式化成时间戳
	 * @param srcTime
	 * @return
	 */
	public static long getFormatMillis(String srcTime) {
		long parseTime = 0L;
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			parseTime = dateFormat.parse(srcTime).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return parseTime;
	}

	/**
	 * 格式化日期
	 * @param srcTime
	 * @param pattern
	 * @return
	 */
	public static String getFormatDate(String srcTime, String pattern) {
		Date date = null;
		SimpleDateFormat srcFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			date = srcFormatter.parse(srcTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		// 更新目标格式
		srcFormatter.applyPattern(pattern);
		String dateString = srcFormatter.format(date);
		return dateString;
	}

	public static boolean getDateExpireState(String srcTime) {
		SimpleDateFormat srcFormatter = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		long currTime = System.currentTimeMillis();
		Date date = null;
		long millis = 0L;
		try {
			date = srcFormatter.parse(srcTime);
			millis = date.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return currTime < millis ? true : false;
	}
	/**
	 * 某年某月某日星期几  flagisweek标识是否需要返回星期几
	 * @return
	 */
	public static String getStringData(String flagisweek){
		 String mYear;
		 String mMonth;
		String mDay;
		 String mWay;
		final Calendar c = Calendar.getInstance();
		c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
		mYear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
		mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
		mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码
		mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
		if("1".equals(mWay)){
			mWay ="天";
		}else if("2".equals(mWay)){
			mWay ="一";
		}else if("3".equals(mWay)){
			mWay ="二";
		}else if("4".equals(mWay)){
			mWay ="三";
		}else if("5".equals(mWay)){
			mWay ="四";
		}else if("6".equals(mWay)){
			mWay ="五";
		}else if("7".equals(mWay)){
			mWay ="六";
		}
		if (flagisweek.equals("no")){
		return mYear + "年" + mMonth + "月" + mDay+"日";
		}else{
			return "星期"+mWay;
		}
	}
	public static boolean isInerTime(){
		Calendar cal = Calendar.getInstance();// 当前日期
		int hour = cal.get(Calendar.HOUR_OF_DAY);// 获取小时
		int minute = cal.get(Calendar.MINUTE);// 获取分钟
		int minuteOfDay = hour * 60 + minute;// 从0:00分开是到目前为止的分钟数
		final int start = 7 * 60 + 30;// 起始时间 07.30的分钟数
		final int end = 18 * 60;// 结束时间 18:00的分钟数
		if (minuteOfDay >= start && minuteOfDay <= end) {
//			System.out.println("在外围内");
			return true;
		} else {
//			System.out.println("在外围外");
			return false;
		}

	}

	public static boolean isOutTime(){
		Calendar cal = Calendar.getInstance();// 当前日期
		int hour = cal.get(Calendar.HOUR_OF_DAY);// 获取小时
		int minute = cal.get(Calendar.MINUTE);// 获取分钟
		int minuteOfDay = hour * 60 + minute;// 从0:00分开是到目前为止的分钟数
		final int start = 18 * 60 + 30;// 起始时间 18.30的分钟数
		final int end = 23 * 60+59;// 结束时间 24:00的分钟数
		if (minuteOfDay >= start && minuteOfDay <= end) {
//			System.out.println("在外围内");
			return true;
		} else {
//			System.out.println("在外围外");
			return false;
		}

	}

	/**
	 * 检测文件是否存在
	 * 
	 * @param path
	 * @return
	 */
	public static boolean checkSourceFile(String path) {
		File f = new File(path);
		if (f != null && f.exists()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 检测目录下是否存在文件
	 * 
	 * @param path
	 * @return
	 */
	public static boolean checkDirectoryFile(String path) {
		File f = new File(path);
		if (f != null && f.isDirectory() && f.list().length > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 图片Path解码成图片，加载到内存
	 * 
	 * @param imgPath
	 * @return
	 */
	public static Bitmap getBitmap(String imgPath) {
		Bitmap iBitMap = null;
		try {
			iBitMap = BitmapFactory.decodeFile(imgPath);
		} catch (Exception e) {
			iBitMap = null;
		} catch (Error e) {
			iBitMap = null;
		}
		return iBitMap;
	}

	/**
	 * 读取Assets文本数据
	 * 
	 */
	public static String readAssets(Context context, String fileName) {
		InputStream is = null;
		String content = null;
		try {
			is = context.getAssets().open(fileName);
			if (is != null) {

				byte[] buffer = new byte[1024];
				ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
				while (true) {
					int readLength = is.read(buffer);
					if (readLength == -1)
						break;
					arrayOutputStream.write(buffer, 0, readLength);
				}
				is.close();
				arrayOutputStream.close();
				content = new String(arrayOutputStream.toByteArray());

			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			content = null;
		} finally {
			try {
				if (is != null)
					is.close();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
		return content;
	}

	/**
	 * 获取Assets中的图片
	 * 
	 * @param context
	 * @param fileName
	 * @return
	 */
	public static Bitmap getAssetsBitmap(Context context, String fileName) {
		Bitmap bitmap = null;
		AssetManager assetManager = context.getResources().getAssets();
		try {
			InputStream is = assetManager.open(fileName);
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	/**
	 * 把BitMap转换为Byte数组
	 * @param bitmap
	 * @return
	 */
	public static byte[] bitmap2Bytes(Bitmap bitmap) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		if (bitmap != null) {
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
		}
		return bos.toByteArray();
	}

	/**
	 * 获取手机软件暂用内存大小，单位为字节
	 * 
	 * @return availableBlocks * blockSize
	 */
	public static long getFileSize(File f) {
		long size = 0;
		try {
			if (f != null && f.exists()) {
				File flist[] = f.listFiles();
				for (int i = 0; i < flist.length; i++) {
					if (flist[i].isDirectory()) {
						size = size + getFileSize(flist[i]);
					} else {
						size = size + flist[i].length();
					}
				}
			}
		} catch (Exception ex) {
			Log.e(TAG, null, ex);
			size = 0;
		}
		return size;
	}

	/**
	 * 删除指定路径下的文件和文件夹
	 * 
	 * @param path
	 */
	public static void deleteSourceFile(String path) {
		File f = new File(path);
		if (null != f) {
			if (f.isDirectory()) {
				File[] file = f.listFiles();
				if (null != file) {
					for (File file2 : file) {
						deleteSourceFile(file2.toString());
						file2.delete();
					}
				}
			} else {
				f.delete();
			}
			f.delete();
		}
	}

	/**
	 * 重命名文件
	 * @param oldFile
	 * @param newFile
	 */
	public static boolean renameFile(String oldFile, String newFile) {
		boolean success = false;
		File file = new File(oldFile);
		if (file != null) {
			success = file.renameTo(new File(newFile));
		}
		return success;
	}

	/**
	 * 保存字符串到SD卡
	 * @param fileName
	 * @param content
	 * @return
	 */
	public static boolean saveContentToSDCard(String fileName, String content) {
		boolean isExternalStorageAvailable = false;  // SD卡可读写的标志位
		FileOutputStream fileOutputStream = null;     // FileOutputStream对象
		// 创建File对象，以SD卡所在的路径作为文件存储路径
		File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), fileName);
		// 判断SD卡是否可读写
		if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			isExternalStorageAvailable = true;
			try {
				fileOutputStream = new FileOutputStream(file);
				// 创建FileOutputStream对象
				fileOutputStream.write(content.getBytes());  // 向FileOutputStream对象中写入数据
				if(fileOutputStream != null) {   // 关闭FileOutputStream对象
					fileOutputStream.close();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return isExternalStorageAvailable;
	}

	/**
	 * 检测网络是否连接
	 * 
	 * @param context   
	 * @return true :  网络连接成功   
	 * @return false :  网络连接失败   
	 */
	public static boolean isNetworkAvailable(Context context) {
		//  获取手机所有连接管理对象（包括对wifi,net等连接的管理）
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivityManager != null) {
			//  获取网络连接管理的对象  
			NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
			// 判断当前网络是否已经连接  
			if (networkInfo != null && networkInfo.isConnected()) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 判断网络状态
	 * @param context
	 * @return
	 */
	public static boolean isMobileNetMode(Context context) {
		boolean isMobileNet = false;
		ConnectivityManager connectMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeInfo = connectMgr.getActiveNetworkInfo();
		if (activeInfo != null) {
			if (activeInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
				isMobileNet = true;
			}
		} else {
			isMobileNet = false;
		}
		return isMobileNet;
	}

	/**
	 * 判断WIFI是否开启
	 * @param context
	 * @return
	 */
	public static boolean isOpenWifi(Context context) {
		WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		return !wifiManager.isWifiEnabled() && wifiManager.getWifiState() != WifiManager.WIFI_STATE_ENABLING;
	}

	/**
	 * 是否开启GPS
	 * @param context
	 * @return
	 */
	public static boolean isOpenGps(final Context context) {
		LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		// 通过GPS卫星定位，定位级别可以精确到街
		return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
	}

	/**
	 * 获取版本VersionName
	 * @param context
	 * @return
	 */
	public static String getVersionName(Context context) {
		String versionName = "";
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return versionName;
	}

	/**
	 * 获取版本VersionCode
	 */
	public static int getVersionCode(Context context) {
		int versioncode = 0;
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versioncode = pi.versionCode;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return versioncode;
	}

	/**
	 *  判断是否含有数字
	 * @param str
	 * @return
     */
	public static boolean isNumeric(String str){
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if( !isNum.matches() ){
			return false;
		}
		return true;
	}

	/**
	 * 获取手机ip地址
	 *
	 * @return
	 */
	public static String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
				NetworkInterface network = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddress = network.getInetAddresses(); enumIpAddress.hasMoreElements(); ) {
					InetAddress inetAddress = enumIpAddress.nextElement();
					if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			return null;
		}
		return null;
	}

	/**
	 * 获取手机号码
	 *
	 * @return
	 */
	public static String getPhoneNum(Context context) {
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		if (tm == null) {
			return "";
		}
		return tm.getLine1Number();
	}

	/**
	 * 获得手机设备惟一ID
	 * @param context
	 * @return
	 */
	public static String getDeviceId(Context context) {
		String deviceId;
		//android.telephony.TelephonyManager
		TelephonyManager mTelephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		if (mTelephony.getDeviceId() != null) {
			deviceId = mTelephony.getDeviceId();
		} else {
			//android.provider.Settings;
			deviceId = Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
		}
		return deviceId;
	}

	/**
	 * 根据uri获取相册中的绝对路径
	 * @param context
	 * @param uri
	 * @return
	 */
	@TargetApi(19)
	public static String getMediaPathFromUri(Context context, Uri uri) {
		String filePath = null;
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
			String[] projection = { MediaStore.Images.Media.DATA };
			Cursor cursor = context.getContentResolver().query(uri, projection,
					null, null, null);
			if (cursor != null) {
				cursor.moveToFirst();
				filePath = cursor.getString(cursor.getColumnIndex(projection[0]));
				cursor.close();
			}
		} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
			String[] projection = { MediaStore.Images.Media.DATA };
			CursorLoader loader = new CursorLoader(context, uri, projection, null,
					null, null);
			Cursor cursor = loader.loadInBackground();
			if (cursor != null) {
				cursor.moveToFirst();
				filePath = cursor.getString(cursor.getColumnIndex(projection[0]));
				cursor.close();
			}
		} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {
			String wholeID = DocumentsContract.getDocumentId(uri);
			// 使用':'分割
			String id = wholeID.split(":")[1];
			String[] projection = { MediaStore.Images.Media.DATA };
			String selection = MediaStore.Images.Media._ID + "=?";
			String[] selectionArgs = { id };
			Cursor cursor = context.getContentResolver().query(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection,
					selection, selectionArgs, null);
			int columnIndex = cursor.getColumnIndex(projection[0]);
			if (cursor.moveToFirst()) {
				filePath = cursor.getString(columnIndex);
			}
			cursor.close();
		} else if ("content".equalsIgnoreCase(uri.getScheme())) {
			if ("com.google.android.apps.photos.content".equals(uri.getAuthority())) {
				filePath = uri.getLastPathSegment();
			} else {
				filePath = getDataColumn(context, uri, null, null);
			}
		} else if ("file".equalsIgnoreCase(uri.getScheme())) {
			filePath = uri.getPath();
		}
		return filePath;
	}

	public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
		Cursor cursor = null;
		String column = MediaStore.Images.Media.DATA;
		String[] projection = { column };
		try {
			cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	/**
	 * SSL证书错误，手动校验https证书
	 *
	 * @param cert      https证书
	 * @param sha256Str sha256值
	 * @return true通过，false失败
	 */
	public static boolean isSSLCertOk(SslCertificate cert, String sha256Str) {
		byte[] SSLSHA256 = hexToBytes(sha256Str);
		Bundle bundle = SslCertificate.saveState(cert);
		if (bundle != null) {
			byte[] bytes = bundle.getByteArray("x509-certificate");
			if (bytes != null) {
				try {
					CertificateFactory cf = CertificateFactory.getInstance("X.509");
					Certificate ca = cf.generateCertificate(new ByteArrayInputStream(bytes));
					MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
					byte[] key = sha256.digest(((X509Certificate) ca).getEncoded());
					return Arrays.equals(key, SSLSHA256);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return false;
	}

	/**
	 * hexString转byteArr
	 * <p>例如：</p>
	 * hexString2Bytes("00A8") returns { 0, (byte) 0xA8 }
	 *
	 * @param hexString
	 * @return 字节数组
	 */
	public static byte[] hexToBytes(String hexString) {

		if (hexString == null || hexString.trim().length() == 0)
			return null;

		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] bytes = new byte[length];
		String hexDigits = "0123456789abcdef";
		for (int i = 0; i < length; i++) {
			int pos = i * 2; // 两个字符对应一个byte
			int h = hexDigits.indexOf(hexChars[pos]) << 4; // 注1
			int l = hexDigits.indexOf(hexChars[pos + 1]); // 注2
			if (h == -1 || l == -1) { // 非16进制字符
				return null;
			}
			bytes[i] = (byte) (h | l);
		}
		return bytes;
	}


}